package com.hefan.api.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.hefan.common.util.StringUtil;
import com.hefan.notify.itf.MessageService;
import com.hefan.user.bean.WatchRelationCacheDao;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WatchCacheService;
import com.hefan.user.itf.WatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author sagagyq
 */
@Component
public class WatchLocalService {

    public static Logger logger = LoggerFactory.getLogger(WatchLocalService.class);

    @Reference
    WatchService watchService;

    @Resource
    JedisService jedisService;

    @Resource
    UserLocalService userLocalService;

    @Reference
    WatchCacheService watchCacheService;
    @Reference
    MessageService messageService;

    /**
     * 关注的主播id串
     *
     * @param userId
     * @return
     */
    public List<String> listWatchId(String userId) {
        return watchCacheService.getAllWatchUserIdList(userId);
    }

    /**
     * 关注
     *
     * @param userId
     * @param mainUserId
     * @param liveRemind
     * @return 返回值 0 正常 1已关注 2主播不存在 3主播被冻结 4主播所在经济公司被冻结 5主播已经被删除 6用户不存在 7用户被删除
     */
    public ResultBean fork(String userId, String mainUserId, Integer liveRemind) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        if(mainUserId.equals(userId)) {
            logger.info("关注操作 自己不能关注自己");
            resultBean.setResult(ResultCode.ParamException);
            return resultBean;
        }
        //检查用户合法性
        resultBean.setResult(checkFork(userId, mainUserId));
        if (resultBean.getCode() == ResultCode.SUCCESS.get_code()) {
            watchService.flushWatchRedis(userId);
            watchService.flushWatchRedis(mainUserId);

            resultBean = watchCacheService.fork(userId, mainUserId);
            if (resultBean.getCode() == ResultCode.SUCCESS.get_code()) {
                watchCacheService.setWatchNumForDay(userId);
                resultBean.setData(watchCacheService.getWatchRelationByUserId(userId, mainUserId));
                forkDB(userId, mainUserId, liveRemind);
            }
        }
        return resultBean;
    }

    @Async
    public int forkDB(String userId, String mainUserId, Integer liveRemind) {
        return watchCacheService.forkDB(userId, mainUserId, liveRemind);
    }

    /**
     * 取消关注
     *
     * @param userId
     * @param mainUserId
     * @return
     */
    public ResultBean unfork(String userId, String mainUserId) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        if (mainUserId.equals(userId)) {
            logger.info("取消关注操作 自己不能取消关注自己，操作错误");
            resultBean.setResult(ResultCode.ParamException);
            return resultBean;
        }
        watchService.flushWatchRedis(userId);
        watchService.flushWatchRedis(mainUserId);
        /*try{
            watchCacheService.refreshFanCacheList(mainUserId);
        }catch (Exception e){
            logger.error("缓存用户userId={}粉丝userId={}关注异常", mainUserId, userId, e);
        }*/
        resultBean = watchCacheService.unfork(userId, mainUserId);
        if (resultBean.getCode() == ResultCode.SUCCESS.get_code()) {
            unforkDB(userId, mainUserId);
        }
        return resultBean;
    }

    @Async
    public int unforkDB(String userId, String mainUserId) {
        return watchCacheService.unforkDB(userId, mainUserId);
    }

    /**
     * 关注的人的信息分页
     *
     * @param pageNo
     * @param pageSize
     * @param userId
     * @param latestScore
     * @return
     */
    @SuppressWarnings("rawtypes")
    public ResultBean listWatchAnchorInfo(int pageNo, int pageSize, String userId, BigDecimal latestScore) {
        return watchCacheService.getWatchListByPage(pageNo, pageSize, userId, latestScore);
    }

    /**
     * 获取用户的关注关系列表
     */
    public List<WatchRelationCacheDao> getAllWatchList(String userId) {
        return watchCacheService.getAllWatchList(userId);
    }

    /**
     * 批量关注
     *
     * @param userId
     * @param mainUserIds
     * @return
     */
    public ResultBean batchFork(String userId, String mainUserIds) {
        ResultBean resultBean = new ResultBean();
        List<String> mainUserIdList = StringUtil.splitToList(",", mainUserIds);
        logger.info("批量关注操作 -Start");
        int successCount = 0;
        for (String mainUserId : mainUserIdList) {
            resultBean = fork(userId, mainUserId, 1);
            if (resultBean.getCode() == ResultCode.SUCCESS.get_code()) {
                successCount++;
            } else {
                logger.info("批量关注操作 -当前关注操作失败：Code=" + resultBean.getCode() + " Msg=" + resultBean.getMsg());
            }
        }
        if (successCount != mainUserIdList.size()) {
            logger.info("批量关注操作 -应关注数：" + mainUserIdList.size() + " 实际关注数：" + successCount);
        }

        logger.info("批量关注操作 -End");
        return new ResultBean(ResultCode.SUCCESS);
    }

    /**
     * 检查用户合法性
     *
     * @param userId
     * @param mainUserId
     * @return
     */
    private ResultCode checkFork(String userId, String mainUserId) {
        WebUser webUser = userLocalService.findUserInfoFromCache(userId);
        if (null == webUser) {
            logger.info("用户不存在：" + userId);
            return ResultCode.userIsDel;
        }

        WebUser mainWebUser = userLocalService.findUserInfoFromCache(mainUserId);
        if (null == mainWebUser) {
            logger.info("被关注用户不存在：" + mainUserId);
            return ResultCode.userIsDel;
        }
        return ResultCode.SUCCESS;
    }

    /**
     * 粉丝列表
     *
     * @param page
     * @param userId
     * @return
     */
    public Page listFansInfo(Page page, String userId) {
        //清空新增粉丝数消息
        messageService.cleanMsgCount(userId, 1);
        return watchService.listFansInfo(page, userId);
    }

    /**
     * 查询关注关系
     *
     * @param userId
     * @param user
     * @return
     */
    public int getWatchRelationByUserId(String userId, String user) {
        return watchCacheService.getWatchRelationByUserId(userId, user);
    }

    /**
     * 关注总数
     *
     * @param userId
     * @return
     */
    public long watchNum(String userId) {
        return watchCacheService.watchNum(userId);
    }

    /**
     * 恢复指定用户的关注关系缓存
     */
    public void recoverWatchRelationCacheByUserId(String userId) {
        watchCacheService.recoverWatchRelationCacheByUserId(userId);
    }

    /**
     * 清空，一次性操作
     */
    @Async
    public void clearWatchRelationCache() {
        watchCacheService.clearWatchRelationCache();
    }

    /**
     * 初始化所有用户的关注关系缓存（谨慎操作）
     */
    @Async
    public void initWatchRelationCache(int userRecordId) {
        watchCacheService.initWatchRelationCache(userRecordId);
    }
}